package plugins

import (
	"strconv"

	"github.com/quarkcloudio/quark-go/v2/pkg/builder"
	"gorm.io/gorm"
)

// 复用（分页参考）
func PageManager(page int, pageSize int) func(*gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

type TransFormIntJudge func(int) bool

// 分页数据转换
func PageManagerGetQuery(c *builder.Context) (int, int) {
	page := TransFormInt(c.Query("page"), 1, func(i int) bool { return i > 0 })

	pageSize := TransFormInt(c.Query("pageSize"), 20, func(i int) bool { return i > 0 })
	return page, pageSize
}

// 默认转整型
func TransFormInt(num interface{}, defaultNum int, judge TransFormIntJudge) int {
	if num == nil {
		return defaultNum
	}
	if tidyNum, err := strconv.Atoi(num.(string)); err != nil {
		return defaultNum
	} else {
		if judge(tidyNum) {
			return tidyNum
		} else {
			return defaultNum
		}
	}
}

// 列表泛型定义
type AutoList[T interface{}] struct {
	List  []T
	Total int64
}
